package com.qf.web;

import com.github.pagehelper.PageInfo;
import com.qf.bean.Dept;
import com.qf.bean.Employee;
import com.qf.bean.Menu;
import com.qf.bean.Role;
import com.qf.service.DeptService;
import com.qf.service.EmployeeService;
import com.qf.service.RoleService;
import com.qf.utils.filter.ExceUtils;
import com.qf.utils.filter.enuml.EmployeeEnum;
import com.qf.utils.filter.enuml.PageEnum;
import com.sun.org.apache.xml.internal.dtm.ref.ExpandedNameTable;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.server.ExportException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * IntelliJ IDEA -> person
 * 2019/11/20 0:13
 *
 * @author zmyao
 * 别看，我是渣渣。
 */
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private DeptService deptService;

/*    @RequestMapping("/login")
    public String login(String loginname, String loginpassword, HttpSession session) {
        Employee employee = employeeService.login(loginname, loginpassword);

        if (employee == null) {
            return "redirect:/login.jsp";
        }
        else {
            session.setAttribute("employee", employee);
            return "redirect:/index.jsp";
        }
    }*/
@RequestMapping("/login")
public String login(HttpServletRequest request) throws Exception {
    System.out.println("login***************************************");
    String  shiroLoginFailure = (String) request.getAttribute("shiroLoginFailure");
  if (shiroLoginFailure != null ){
      if (UnknownAccountException.class.getName().equals(shiroLoginFailure)){
          throw  new Exception("账户错误");
      }
      else  if (IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)){
          throw  new Exception("密码错误");
      }
      else {
          throw  new Exception("未知异常");
      }
  }
    System.out.println("------------------------------login");
    return  "login";
}
 /*   @RequestMapping("/loginout")
    public String loginout(HttpSession session) {
        session.invalidate();
        return "redirect:/login.jsp";
    }*/

    @RequestMapping("/resource/demo2/getemployees")
    @RequiresPermissions("employee:getemplouees")
    public String findAll(@RequestParam(defaultValue = "1") int index, ModelMap modelMap, String username, String rname, String deptname) {

        PageInfo<Employee> pageInfo = employeeService.findAll(index, PageEnum.PAGESIZE.getSize(), username, rname, deptname);
        modelMap.addAttribute("pageInfo", pageInfo);
        modelMap.addAttribute("username", username);
        modelMap.addAttribute("rname", rname);
        modelMap.addAttribute("deptname", deptname);
        return "resource/demo2/list";
    }

    @RequestMapping("/resource/demo2/insertEmp")
    public void insert(Employee emp, HttpServletResponse response) throws IOException {
        emp.setCreatedate(new Date());
        emp.setState(1);//1表示未删除， 0 表示已删除
        int i = employeeService.insert(emp);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        if (i == -1) {
            out.print("<script type='text/javascript'>alert('登录账号已经存在!');location.href='/resource/demo2/getalldepts';</script>");
        } else if (i > 0) {
            out.print("<script type='text/javascript'>alert('添加成功!');location.href='/resource/demo2/getemployees';</script>");
        } else {
            out.print("<script type='text/javascript'>alert('添加失败!请选择部门或者职位');location.href='/resource/demo2/getalldepts';</script>");
        }
    }

    @RequestMapping("/resource/demo2/findByLoginname")
    @ResponseBody
    public Map findByLoginname(String loginname, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        Map map = new HashMap();
        Employee employee = employeeService.findByLoginname(loginname);
        if (employee != null) {
            map.put("message", "您输入的用户名已经存在");
            return map;
        }
        map.put("message", "ok");
        return map;
    }

    @RequestMapping("/resource/demo2/findEmpbyid")
    public String findEmpbyid(int id, ModelMap map) {
        Employee employee = employeeService.selectByPrimaryKey(id);
        Integer deptid = employee.getDeptid();
        List<Dept> depts = deptService.findalldepts();
        List<Role> roles = roleService.getallrolesByDid(deptid);
        map.addAttribute("employee", employee);
        map.addAttribute("roles", roles);
        map.addAttribute("depts", depts);
        return "resource/demo2/update";
    }

    @RequestMapping("/resource/demo2/updateEmp")
    public void updateEmp(Employee employee, HttpServletResponse response, int id) {
        try {
            int i = employeeService.updateEmp(employee);
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            if (i > 0) {
                out.print("<script type='text/javascript'>alert('修改成功!');location.href='/resource/demo2/getemployees';</script>");
            } else {
                out.print("<script type='text/javascript'>alert('修改失败!');location.href='/resource/demo2/findEmpbyid?id=" + id + "';</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @RequestMapping("/resource/demo2/deleteById")
    public void deleteByid(int id, HttpServletResponse response) {
        int len = employeeService.deleteByid(id, EmployeeEnum.DELETE.getState());
        if (len > 0) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                if (len > 0) {
                    out.print("<script type='text/javascript'>alert('删除成功!');location.href='/resource/demo2/getemployees';</script>");
                } else {
                    out.print("<script type='text/javascript'>alert('删除失败!');location.href='/resource/demo2/getemployees';</script>");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    @RequestMapping("/resource/demo2/deleteByIds")
    public void deleteByIds(int[] empids, HttpServletResponse response, String method) {
        PrintWriter out = null;
        try {
            response.setContentType("text/html;charset=utf-8");
          out  = response.getWriter();
          if (empids == null){
              out.print("<script type='text/javascript'>alert('您没有选中任何选项!');location.href='/resource/demo2/getemployees';</script>");
          }
            if ("delete".equals(method)) {
                int len = employeeService.deleteByIds(empids);
                if (len > 0) {
                    out.print("<script type='text/javascript'>alert('删除成功!');location.href='/resource/demo2/getemployees';</script>");
                } else {
                    out.print("<script type='text/javascript'>alert('删除失败!');location.href='/resource/demo2/getemployees';</script>");
                }
            } else if ("export".equals(method)) {
                try {
                    List<Employee> employeeList = employeeService.findByIds(empids);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    ExceUtils.createFirst("用户信息" + sdf);
                    ExceUtils.createOthers(employeeList);
                    ExceUtils.export(new FileOutputStream("e://" + (sdf.format(new Date())) + ".xls"));
                    out.print("<script type='text/javascript'>alert('导出成功!');location.href='/resource/demo2/getemployees';</script>");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
             if (out != null){
                 out.close();
             }
        }

    }

}
